//
//  MoreMenusViewController.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/5/17.
//

import UIKit

class MoreMenusViewController: CommonViewController {
    private var myMenus:Array<CustomMenuView>!
    private var bigMenus:Array<RecommendBigMenuView>!
    private let contentView = UIView()
    private let line = UIView.SeparatorLine()
    private var menusBar:RecommendMenuBarView!
    private let menuBarView = UIView()
    private let recomendScroll = UIScrollView()
    private var line_y:CGFloat = 0.0
    private var isTop:Bool = false // 是否已吸顶
    private let scroll = UIScrollView()
    private var tabIndex = 0
    private var isPress = false
    private var isDragging = true
    private let editButton = UIButton(type: .custom)
    private let headerView = UIView()
    private var tipArray:Array<UILabel> = []
    private var recommendItems:Array<Array<RecommendMenuView>> = []
    private let recommendLabel = UILabel()
    private let tipLabel = UILabel()
    var currentSelectedIndex = 1
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        statusBarStyle = .lightContent
        self.view.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0)
        view.addSubview(contentView)
        contentView.backgroundColor = .white
        contentView.setRadiusAndDirection(radius: 10, directions: [.topLeft,.topRight])
        contentView.snp.makeConstraints({
            $0.top.equalTo(ScreenHeight)
            $0.height.equalTo(ScreenHeight-UIApplication.shared.statusBarFrame.height)
            $0.left.right.equalTo(0)
        })
       
        let closeButton = UIButton(type: .custom)
        closeButton.contentEdgeInsets = UIEdgeInsets.init(top: 5, left: 5, bottom: 0, right: 0)
        closeButton.addTarget(self, action: #selector(closeTap), for: .touchUpInside)
        closeButton.setImage(UIImage(named: "close")?.reSizeImage(reSize: CGSize(width: 20, height: 20)), for: .normal)
        contentView.addSubview(closeButton)
        closeButton.snp.makeConstraints({
            $0.left.top.equalTo(15)
        })
        let searchButton = UIButton(type: .custom)
        searchButton.contentEdgeInsets = UIEdgeInsets.init(top: 5, left: 0, bottom: 0, right: 5)
        searchButton.addTarget(self, action: #selector(searchTap), for: .touchUpInside)
        searchButton.setImage(UIImage(named: "search")?.reSizeImage(reSize: CGSize(width: 20, height: 20)), for: .normal)
        contentView.addSubview(searchButton)
        searchButton.snp.makeConstraints({
            $0.top.equalTo(15)
            $0.right.equalToSuperview().inset(15)
        })
        contentView.addSubview(line)
        line.isHidden = true
        line.snp.makeConstraints({
            $0.top.equalTo(closeButton.snp.bottom).offset(15)
            $0.left.right.equalTo(0)
            $0.height.equalTo(1)
        })
        
        scroll.delegate = self
        scroll.showsVerticalScrollIndicator = false
        contentView.addSubview(scroll)
        scroll.snp.makeConstraints({
            $0.top.equalTo(closeButton.snp.bottom).offset(16)
            $0.left.right.bottom.equalTo(0)
            $0.width.equalTo(ScreenWidth)
        })
        scroll.addSubview(headerView)
        headerView.snp.makeConstraints({
            $0.left.top.right.equalTo(0)
            $0.width.equalToSuperview()
        })
        let titleLabel = UILabel()
        titleLabel.text = "我的频道"
        titleLabel.font = Font_Size_16
        titleLabel.textColor = B000_COLOR
        headerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints({
            $0.left.equalTo(15)
            $0.top.equalTo(0)
            $0.bottom.equalToSuperview().inset(15)
        })
        
        let messageLabel = UILabel()
        messageLabel.text = "点击进入频道"
        messageLabel.textColor = B999_TITLE_COLOR
        messageLabel.font = Font_Size_12
        headerView.addSubview(messageLabel)
        messageLabel.snp.makeConstraints({
            $0.left.equalTo(titleLabel.snp.right).offset(5)
            $0.centerY.equalTo(titleLabel)
        })
        
        editButton.contentEdgeInsets = UIEdgeInsets.init(top: 5, left: 15, bottom: 5, right: 15)
        editButton.addTarget(self, action: #selector(editPress(btn:)), for: .touchUpInside)
        editButton.setTitle("编辑", for: .normal)
        editButton.setTitle("完成", for: .selected)
        editButton.setTitleColor(RED_COLOR, for: .normal)
        editButton.setTitleColor(RED_COLOR, for: .selected)
        editButton.font = Font_Size_14
        headerView.addSubview(editButton)
        editButton.snp.makeConstraints({
            $0.right.equalToSuperview()
            $0.bottom.equalTo(titleLabel.snp.bottom)
        })
        
        let myMenusTitles = ["关注","推荐","热榜","抗疫","北京","视频","要闻","新时代","小视频","问答","音乐","国际","直播","军事","财经","影视","懂车帝","科技","美食","情感","体育","健康","图片","历史","东奥","NBA","免费小说","音频"]
        myMenus = []
        for i in 0..<myMenusTitles.count {
            let name = myMenusTitles[i]
            let menu = CustomMenuView(title: name, canRemove: i>=2 ? true:false)
            menu.titleButton.isSelected = currentSelectedIndex == i
            menu.delegate = self
            scroll.addSubview(menu)
            myMenus.append(menu)
        }
        
        recommendLabel.text = "为你推荐"
        recommendLabel.font = Font_Size_16
        recommendLabel.textColor = B000_COLOR
        scroll.addSubview(recommendLabel)
        recommendLabel.snp.makeConstraints({
            $0.left.equalTo(15)
            $0.top.equalTo(myMenus.last!.snp.bottom).offset(15)
        })
        
        self.updateCustomMenusLayout()

        tipLabel.text = "点击进入频道"
        tipLabel.textColor = B999_TITLE_COLOR
        tipLabel.font = Font_Size_12
        scroll.addSubview(tipLabel)
        tipLabel.snp.makeConstraints({
            $0.left.equalTo(recommendLabel.snp.right).offset(5)
            $0.centerY.equalTo(recommendLabel)
        })
        
        scroll.addSubview(recomendScroll)
        recomendScroll.snp.makeConstraints({
            $0.left.right.equalTo(0)
            $0.top.equalTo(recommendLabel.snp.bottom).offset(15)
            $0.width.equalToSuperview()
        })
        recomendScroll.showsHorizontalScrollIndicator = false
        
        bigMenus = []
        for i in 0...5 {
            let menu = RecommendBigMenuView.init(title: "精品课\(i+1)", message: "精品好课不断更新", icon: "wuhen", bgColor: Separator_COLOR){
                [weak self] in
                self?.addBigMenu(title: "精品课\(i+1)")
            }
            recomendScroll.addSubview(menu)
            bigMenus.append(menu)
            
        }
        self.updateBigMenus()
        
        scroll.addSubview(menuBarView)
        menuBarView.snp.makeConstraints({
            $0.top.equalTo(recomendScroll.snp.bottom).offset(15)
            $0.height.equalTo(50)
            $0.left.right.equalTo(0)
        })
        let barTitles = ["热门精选","生活娱乐","体育财经","科教文艺","其他"]
        
        menusBar = RecommendMenuBarView.init(titles: barTitles)
        menuBarView.addSubview(menusBar)
        menusBar.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        let hot = ["微头条","圈子","热点","房产","数码","搞笑","手机","电影","三农"]
        let yule = ["健身","时尚","育儿","养生","旅游","宠物","家居","收藏","星座"]
        let tiyu = ["股票","彩票"]
        let wenyi = ["传媒","美文","国风","教育","文化","科学","故事","精选","辟谣","正能量"]
        let qita = ["党媒推荐","漫画","政法","小康","生活","动漫","值点","公益"]
        let margin:CGFloat = 15
        let items = [hot,yule,tiyu,wenyi,qita]
        for i in 0..<items.count {
            let label = UILabel()
            label.text = barTitles[i]
            label.font = Font_Size_14
            label.textColor = B999_TITLE_COLOR
            scroll.addSubview(label)
            tipArray.append(label)
            var templist:Array<RecommendMenuView> = []
            for j in 0..<items[i].count {
                let name = items[i][j]
                let menu = RecommendMenuView(title: name,point: (i,j)){[weak self]in
                    self?.addCustomMenu(title: name)
                }
                scroll.addSubview(menu)
                templist.append(menu)
            }
            recommendItems.append(templist)
        }
        self.updateRecommendItemView()

        contentView.addGestureRecognizer(UIPanGestureRecognizer.init(target: self, action: #selector(panView(pan:))))
        NotificationMananger.addNotification(.Custom(name: "EditBegin"), target: self, selector: #selector(editBegin))
        menusBar.tabSelectedChanged = { [weak self] index in
            self?.tabIndex = index
            self?.isPress = true
            let label = self?.tipArray[index]
            let miny = label!.frame.origin.y - (self?.menuBarView.frame.height)! - margin
            self?.scroll.setContentOffset(CGPoint.init(x: 0, y: miny), animated: true)
        }
        self.scroll.layoutIfNeeded()
        self.resetScrollContentSize()
    }
    
    @objc func editBegin(){
        guard editButton.isSelected == false else {
            return
        }
        self.editPress(btn: editButton)
    }
    @objc func panView(pan:UIPanGestureRecognizer){
        let point = pan.translation(in: view)
        if pan.state == .changed {
            if point.y>=0 {
                contentView.snp.remakeConstraints({
                    $0.top.equalTo(UIApplication.shared.statusBarFrame.height+point.y)
                    $0.left.bottom.right.equalTo(0)
                })
                self.view.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 1 - point.y/ScreenHeight)
            }
        }else if pan.state == .ended {
            if  point.y > ScreenHeight/2 {
                self.dismissView()
            }else{
                contentView.snp.remakeConstraints({
                    $0.top.equalTo(UIApplication.shared.statusBarFrame.height)
                    $0.left.bottom.right.equalTo(0)
                })
            }
        }
        self.view.layoutIfNeeded()
    }
 
    @objc func dismissView(){
        NotificationMananger.removeAllNotifocation(self)
        contentView.snp.remakeConstraints({
            $0.width.centerX.equalToSuperview()
            $0.top.equalTo(ScreenHeight)
        })
        UIView.animate(withDuration: 0.3) {
            self.view.layoutIfNeeded()
            self.view.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.0)
        }completion: { (res) in
            self.dismiss(animated: false, completion: {
                
            })
        }
    }
    @objc func editPress(btn:UIButton){
        btn.isSelected = !btn.isSelected
        for item in myMenus{
            item.isHiddenClose = !btn.isSelected
            if btn.isSelected {
                item.startAnimation()
            }else{
                item.stopAnimation()
            }
        }
    }
    @objc func searchTap(){
        SystemLog("search")
    }
    @objc func closeTap(){
        self.dismissView()
    }
    func updateCustomMenusLayout() {
        let margin:CGFloat = 15
        let itemSize = CGSize.init(width: (ScreenWidth-5*margin)/4, height: 40)
        var temp:UIView?
        for i in 0..<myMenus.count {
            let mView = myMenus[i]
            mView.snp.remakeConstraints({
                if i % 4 == 0{
                    $0.left.equalTo(margin)
                    if temp == nil{
                        $0.top.equalTo(headerView.snp.bottom).offset(margin)
                    }else{
                        $0.top.equalTo((temp?.snp.bottom)!).offset(margin)
                    }
                }else{
                    $0.left.equalTo((temp?.snp.right)!).offset(margin)
                    $0.top.equalTo((temp?.snp.top)!)
                }
                $0.size.equalTo(itemSize)
            })
            temp = mView
        }
        recommendLabel.snp.remakeConstraints({
            $0.left.equalTo(15)
            $0.top.equalTo(myMenus.last!.snp.bottom).offset(15)
        })
//        UIView.animate(withDuration: 0.3) {
//            self.scroll.layoutIfNeeded()
//        }
        
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        contentView.snp.remakeConstraints({
            $0.top.equalTo(UIApplication.shared.statusBarFrame.height)
            $0.left.bottom.right.equalTo(0)
        })
        UIView.animate(withDuration: 0.5) {
            self.view.layoutIfNeeded()
            self.view.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 1)
        }
    }
    // 更新tuijianyueshu
    func updateRecommendItemView(){
        var temp:UIView?
        let margin:CGFloat = 15
        let itemSize = CGSize.init(width: (ScreenWidth-5*margin)/4, height: 40)
        for i in 0..<tipArray.count {
            let label = tipArray[i]
            label.snp.remakeConstraints({
                $0.left.equalTo(15)
                if temp == nil{
                    $0.top.equalTo(menuBarView.snp.bottom).offset(margin)
                }else{
                    $0.top.equalTo(temp!.snp.bottom).offset(margin)
                }
            })
            temp = label
            for j in 0..<recommendItems[i].count {
                let tempMenu = recommendItems[i][j]
                tempMenu.point = (i,j)
                tempMenu.snp.remakeConstraints({
                    if j % 4 == 0 {
                        $0.left.equalTo(label.snp.left)
                        $0.top.equalTo((temp?.snp.bottom)!).offset(margin)
                    }else{
                        $0.left.equalTo((temp?.snp.right)!).offset(margin)
                        $0.top.equalTo((temp?.snp.top)!)
                    }
                    $0.size.equalTo(itemSize)
                    if i == tipArray.count-1 && j == recommendItems[i].count-1  {
                        $0.bottom.equalToSuperview()
                    }
                })
                temp = tempMenu
            }
        }
//        UIView.animate(withDuration: 0.3) {
//            self.scroll.layoutIfNeeded()
//        }
    }
    func resetScrollContentSize(){
        let margin:CGFloat = 15
        let itemSize = CGSize.init(width: (ScreenWidth-5*margin)/4, height: 40)
        var size = scroll.contentSize
        let label_y = tipArray.last?.frame.origin.y
        
        let last_y = (recommendItems.last?.last?.frame.origin.y)! + itemSize.height+margin
        if last_y - label_y! < scroll.frame.height {
            size.height = label_y! + scroll.frame.height - (last_y - label_y!) + menuBarView.frame.height
            scroll.contentSize = size
        }
    }
    // 点击推荐项添加频道
    func addBigMenu(title:String) {
        let index = bigMenus.firstIndex { (item) -> Bool in
            return item.title == title
        }
        let big = bigMenus[index!]
        
        let menu = CustomMenuView(title: title, canRemove: true)
        menu.alpha = 0
        menu.titleButton.isSelected = false
        menu.delegate = self
        scroll.addSubview(menu)
        menu.snp.makeConstraints({
            $0.edges.equalTo(big)
        })
        self.scroll.layoutIfNeeded()
        menu.snp.remakeConstraints({
            $0.edges.equalTo(myMenus.last!)
        })
        bigMenus.remove(at: index!)
        self.updateBigMenus()
        myMenus.append(menu)
        if bigMenus.count == 0 {
            recommendLabel.removeFromSuperview()
            tipLabel.removeFromSuperview()
            recomendScroll.removeFromSuperview()
            menuBarView.snp.remakeConstraints({
                $0.top.equalTo(myMenus.last!.snp.bottom).offset(15)
                $0.height.equalTo(50)
                $0.left.right.equalTo(0)
            })
        }
        self.updateCustomMenusLayout()
        UIView.animate(withDuration: 0.3) {
            self.scroll.layoutIfNeeded()
            menu.alpha = 1
            big.alpha = 0
        }completion: { (res) in
            big.removeFromSuperview()
            self.resetScrollContentSize()
        }
        
    }
    // 更新推荐项约束
    func updateBigMenus() {
        guard bigMenus.count>0 else {
            return
        }
        var temp:UIView?
        for i in 0..<bigMenus.count {
            let menu = bigMenus[i]
            menu.snp.remakeConstraints({
                if temp == nil{
                    $0.left.equalTo(15)
                }else{
                    $0.left.equalTo((temp?.snp.right)!).offset(15)
                }
                $0.top.bottom.equalTo(0)
                $0.height.equalToSuperview()
                $0.width.equalTo(150)
                if i == bigMenus.count-1{
                    $0.right.equalToSuperview().inset(15)
                }
            })
            temp = menu
        }
    }
    // 点击下方按钮添加频道
    func addCustomMenu(title:String) {
        let temp = recommendItems.first { (items) -> Bool in
            return items.first { (item) -> Bool in
                return item.title == title
            }?.title == title
        }?.first(where: { (item) -> Bool in
            return item.title == title
        })
        SystemLog(temp?.title)
        let menu = CustomMenuView(title: title, canRemove: true)
        menu.alpha = 0
        menu.titleButton.isSelected = false
        menu.delegate = self
        scroll.addSubview(menu)
        menu.snp.makeConstraints({
            $0.edges.equalTo(temp!)
        })
        self.scroll.layoutIfNeeded()
        menu.snp.remakeConstraints({
            $0.edges.equalTo(myMenus.last!)
        })
        recommendItems[temp!.point.0].remove(at: temp!.point.1)
        self.updateRecommendItemView()
        myMenus.append(menu)
        self.updateCustomMenusLayout()
        UIView.animate(withDuration: 0.3) {
            self.scroll.layoutIfNeeded()
            menu.alpha = 1
            temp?.alpha = 0
        }completion: { (res) in
            temp?.removeFromSuperview()
            self.resetScrollContentSize()
        }
    }
}
extension MoreMenusViewController:CustomMenuViewDelegate{
    func deleteTap(title: String) {
        let index = myMenus.firstIndex { (temp) -> Bool in
            return temp.titleButton.currentTitle == title
        }
        let item = RecommendMenuView(title: title,point: (0,0)){[weak self]in
            self?.addCustomMenu(title: title)
        }
        scroll.addSubview(item)
        item.alpha = 0
        item.snp.makeConstraints({
            $0.edges.equalTo(recommendItems.first!.first!)
        })
        self.scroll.layoutIfNeeded()
        recommendItems[item.point.0].insert(item, at: item.point.1)
        self.updateRecommendItemView()
        let menu = myMenus[index!]
        menu.stopAnimation()
        myMenus.remove(at: index!)
        self.updateCustomMenusLayout()
        menu.snp.remakeConstraints({
            $0.edges.equalTo(recommendItems.first!.first!)
        })
        UIView.animate(withDuration: 0.3) {
            self.scroll.layoutIfNeeded()
            item.alpha = 1
            menu.alpha = 0
        }completion: { (res) in
            menu.removeFromSuperview()
        }
    }
}


extension MoreMenusViewController:UIScrollViewDelegate{
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        self.isPress = false
        SystemLog("scrollViewDidEndScrollingAnimation")
    }
   
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offsety = scrollView.contentOffset.y
        let bar_y = menuBarView.frame.origin.y
        if offsety>=bar_y {
            if !isTop{
                view.addSubview(menusBar)
                menusBar.snp.remakeConstraints({
                    $0.top.equalTo(line.snp.bottom)
                    $0.height.equalTo(50)
                    $0.left.right.equalTo(0)
                })
                isTop = true
            }
            if isTop && !isPress{
                if offsety>=(tipArray.last!.frame.origin.y-menuBarView.frame.height - 15) {
                    self.tabIndex = tipArray.count-1
                    self.menusBar.nextTab(tipArray.count-1)
                }else{
                    for i in 0..<tipArray.count-1 {
                        let y1 = tipArray[i].frame.origin.y - menuBarView.frame.height - 15
                        let y2 = tipArray[i+1].frame.origin.y - menuBarView.frame.height - 15
                        if offsety>y1 && offsety<y2 {
                            self.tabIndex = i
                            self.menusBar.nextTab(i)
                        }
                    }
                }
            }
        }else{
            if isTop {
                menuBarView.addSubview(menusBar)
                menusBar.snp.remakeConstraints({
                    if bigMenus.count == 0{
                        $0.top.equalTo(myMenus.last!.snp.bottom).offset(15)
                    }else{
                        $0.top.equalTo(recomendScroll.snp.bottom).offset(15)
                    }
                    $0.height.equalTo(50)
                    $0.left.right.equalTo(0)
                })
                isTop = false
            }
        }
        self.line.isHidden = offsety<=0 ? true : isTop
    }
}
